package com.surfacing.rcp.server.listener;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.surfacing.rcp.db.dao.DoctorDAO;
import com.surfacing.rcp.db.dao.factory.DaoFactory;
import com.surfacing.rcp.model.QueryFilter;
import com.surfacing.rcp.model.common.AbstractMessage;
import com.surfacing.rcp.model.common.IFilterTypes;
import com.surfacing.rcp.model.entity.DAOException;
import com.surfacing.rcp.model.entity.Doctor;

/**
 * This class will be notified uppon Doctor changes
 * 
 */
public class DoctorListener extends ServerListenerAdapter {
	private DoctorDAO staffDao = DaoFactory.MYSQL.createDoctorDAO();

	@Override
	public AbstractMessage handleAddRequest(AbstractMessage addObject)
			throws DAOException, SQLException {
		Doctor addMember = (Doctor) addObject;
		if (!staffDao.addDoctor(addMember))
			throw new DAOException("DoctorListener",
					"Failed to add the Doctor: " + addMember);
		return addMember;
	}

	/**
	 * Update of a Doctor
	 */
	@Override
	public AbstractMessage handleUpdateRequest(AbstractMessage updateObject)
			throws DAOException, SQLException {
		Doctor updateMember = (Doctor) updateObject;
		if (!staffDao.updateDoctor(updateMember))
			throw new DAOException("DoctorListener",
					"Failed to update the Doctor: " + updateMember);
		return updateMember;
	}

	/**
	 * Listing of all members
	 */
	@Override
	public ArrayList<AbstractMessage> handleListingRequest(
			QueryFilter queryFilter) throws DAOException, SQLException {
		ArrayList<AbstractMessage> list = new ArrayList<AbstractMessage>();
		List<Doctor> memberList;
		// if there is no filter -> request all
		if (queryFilter == null || queryFilter.getFilterList().isEmpty()) {
			memberList = staffDao.getAllDoctor();
			if (memberList == null)
				throw new DAOException("DoctorListener",
						"Failed to list all Doctors");
			list.addAll(memberList);
		} else if (queryFilter.containsFilterType(IFilterTypes.ID_FILTER)) {
			// get the query filter
			final String filter = queryFilter
					.getFilterValue(IFilterTypes.ID_FILTER);
			int id = Integer.parseInt(filter);
			Doctor member = staffDao.getDoctorByID(id);
			if (member == null)
				throw new DAOException("DoctorListener",
						"Failed to get the Doctor by id:" + id);
			list.add(member);
		}
		return list;
	}
}